<template>
  <div class="statistics-page">
    <el-scrollbar height="calc(100vh - 100px)">
      <el-card v-for="activity in statistics" :key="activity.activityId" class="activity-card">
        <template #header>
          <div class="card-header">
            <div class="header-left">
              <el-tag :type="getTypeTag(activity.type)" size="large" class="type-tag">
                {{ getActivityType(activity.type) }}
              </el-tag>
              <span class="time-info">
                {{ formatDateTime(activity.startTime) }} 至 {{ formatDateTime(activity.endTime) }}
              </span>
            </div>
            <div class="header-right">
              <el-tag :type="getTimeStatusType(activity)">
                {{ getTimeStatus(activity) }}
              </el-tag>
            </div>
          </div>
        </template>

        <!-- 签到统计信息 -->
        <div class="statistics-info">
          <div class="info-item">
            <span class="label">总人数：</span>
            <span class="value">{{ activity.totalCount || 0 }}人</span>
          </div>
          <div class="info-item">
            <span class="label">已签到：</span>
            <span class="value success">{{ activity.signedCount || 0 }}人</span>
          </div>
          <div class="info-item">
            <span class="label">未签到：</span>
            <span class="value warning">{{ (activity.totalCount || 0) - (activity.signedCount || 0) }}人</span>
          </div>
          <div class="info-item">
            <span class="label">签到率：</span>
            <span class="value">{{ calculateSignRate(activity) }}%</span>
          </div>
        </div>

        <!-- 签到进度条 -->
        <el-progress 
          :percentage="calculateSignRate(activity)" 
          :status="getProgressStatus(activity)"
          :stroke-width="20"
          class="sign-progress"
        />

        <!-- 学生签到详情 -->
        <div class="students-detail">
          <el-tabs type="border-card" v-model="activeTab">
            <el-tab-pane label="已签到学生" name="signed">
              <div class="table-container">
                <el-table 
                  v-if="activeTab === 'signed'"
                  :data="activity.signedStudents || []" 
                  style="width: 100%" 
                  size="large"
                  height="300"
                >
                  <el-table-column prop="realName" label="姓名" width="120" align="center" />
                  <el-table-column prop="username" label="学号" width="120" align="center" />
                  <el-table-column prop="signTime" label="签到时间" align="center">
                    <template #default="{ row }">
                      {{ formatDateTime(row.signTime) }}
                    </template>
                  </el-table-column>
                </el-table>
                <el-empty 
                  v-if="activeTab === 'signed' && (!activity.signedStudents || activity.signedStudents.length === 0)" 
                  description="暂无已签到学生" 
                />
              </div>
            </el-tab-pane>
            <el-tab-pane label="未签到学生" name="unsigned">
              <div class="table-container">
                <el-table 
                  v-if="activeTab === 'unsigned'"
                  :data="activity.unsignedStudents || []" 
                  style="width: 100%" 
                  size="large"
                  height="300"
                >
                  <el-table-column prop="realName" label="姓名" width="120" align="center" />
                  <el-table-column prop="username" label="学号" width="120" align="center" />
                  <el-table-column label="签到时间" align="center">
                    <template #default>
                      <el-tag type="warning" size="small">未签到</el-tag>
                    </template>
                  </el-table-column>
                </el-table>
                <el-empty 
                  v-if="activeTab === 'unsigned' && (!activity.unsignedStudents || activity.unsignedStudents.length === 0)" 
                  description="暂无未签到学生" 
                />
              </div>
            </el-tab-pane>
          </el-tabs>
        </div>
      </el-card>

      <!-- 空状态显示 -->
      <el-empty v-if="!statistics || statistics.length === 0" description="暂无签到活动" />
    </el-scrollbar>

    <!-- 刷新按钮 -->
    <el-affix position="bottom" :offset="20" style="position: absolute; right: 20px;">
      <el-button
        type="primary"
        circle
        @click="fetchStatistics"
        :loading="loading"
      >
        <el-icon><Refresh /></el-icon>
      </el-button>
    </el-affix>
  </div>
</template>

<script>
export default {
  name: 'TeacherStatisticsPage'
}
</script>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { Refresh } from '@element-plus/icons-vue'
import { getSignStatistics } from '@/api/teacher'

const loading = ref(false)
const rawStatistics = ref(null)
const activeTab = ref('signed')

// 处理后的统计数据
const statistics = computed(() => {
  if (!rawStatistics.value) return []
  
  return rawStatistics.value
    .map(activity => ({
      ...activity,
      id: activity.activityId,
      totalCount: activity.totalStudents
    }))
    .sort((a, b) => {
      // 如果两个活动都已截止，按照结束时间降序排序
      if (a.remainingMinutes === null && b.remainingMinutes === null) {
        return new Date(b.endTime).getTime() - new Date(a.endTime).getTime()
      }
      
      // 已截止的活动排在后面
      if (a.remainingMinutes === null) return 1
      if (b.remainingMinutes === null) return -1
      
      // 按剩余时间降序排序
      return b.remainingMinutes - a.remainingMinutes
    })
})

// 获取活动类型
const getActivityType = (type) => {
  const types = {
    normal: '普通签到',
    code: '签到码',
    qr: '二维码',
    gesture: '九宫格',
    location: '位置签到'
  }
  return types[type] || type
}

// 获取类型标签样式
const getTypeTag = (type) => {
  const tags = {
    normal: '',
    code: 'warning',
    qr: 'success',
    gesture: 'info',
    location: 'danger'

  }
  return tags[type] || 'info'
}

// 格式化日期时间
const formatDateTime = (dateStr) => {
  if (!dateStr) return ''
  const date = new Date(dateStr)
  const year = date.getFullYear()
  const month = (date.getMonth() + 1).toString()
  const day = date.getDate().toString()
  const hour = date.getHours().toString().padStart(2, '0')
  const minute = date.getMinutes().toString().padStart(2, '0')
  const second = date.getSeconds().toString().padStart(2, '0')
  return `${year}年${month}月${day}日${hour}时${minute}分${second}秒`
}

// 计算签到率
const calculateSignRate = (activity) => {
  if (!activity.totalStudents || activity.totalStudents === 0) return 0
  return Math.round((activity.signedCount || 0) / activity.totalStudents * 100)
}

// 获取时间状态
const getTimeStatus = (activity) => {
  if (activity.timeStatus === '已截止') return '已结束'
  if (activity.remainingMinutes === null) return '已结束'
  if (activity.remainingMinutes <= 0) return '已结束'
  
  const now = new Date().getTime()
  const startTime = new Date(activity.startTime).getTime()
  
  if (now < startTime) return '未开始'
  return activity.timeStatus || '进行中'
}

// 获取时间状态标签类型
const getTimeStatusType = (activity) => {
  const status = getTimeStatus(activity)
  switch (status) {
    case '已结束':
      return 'danger'
    case '未开始':
      return 'info'
    default:
      return 'success'
  }
}

// 获取进度条状态
const getProgressStatus = (activity) => {
  const rate = calculateSignRate(activity)
  if (rate === 100) return 'success'
  if (rate >= 80) return ''
  return 'warning'
}

// 获取统计数据
const fetchStatistics = async () => {
  loading.value = true
  try {
    const response = await getSignStatistics()
    if (response.code === 200) {
      rawStatistics.value = response.data
    } else {
      ElMessage.error(response.message || '获取统计数据失败')
    }
  } catch (error) {
    console.error('获取统计数据失败:', error)
    ElMessage.error('获取统计数据失败')
  } finally {
    loading.value = false
  }
}

// 页面加载时获取统计数据
onMounted(() => {
  fetchStatistics()
})
</script>

<style scoped>
.statistics-page {
  height: calc(100vh - 60px);
  position: relative;
  padding: 20px;
  box-sizing: border-box;
}

.activity-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 12px;
}

.type-tag {
  min-width: 80px;
  text-align: center;
}

.time-info {
  color: #606266;
  font-size: 14px;
}

.statistics-info {
  display: flex;
  flex-wrap: wrap;
  gap: 40px;
  margin: 20px 0;
}

.info-item {
  display: flex;
  align-items: center;
  gap: 8px;
}

.info-item .label {
  color: #606266;
}

.info-item .value {
  font-size: 16px;
  font-weight: bold;
}

.info-item .value.success {
  color: #67C23A;
}

.info-item .value.warning {
  color: #E6A23C;
}

.sign-progress {
  margin: 20px 0;
}

.students-detail {
  margin-top: 20px;
}

.table-container {
  padding: 10px;
}

:deep(.el-tabs--border-card) {
  box-shadow: none;
  border: 1px solid #dcdfe6;
}

:deep(.el-table) {
  margin: 0;
}

:deep(.el-table__header) {
  background-color: #f5f7fa;
}

:deep(.el-table__row) {
  height: 50px;
}

:deep(.el-table__empty-block) {
  height: 260px;
}

:deep(.el-tabs__header) {
  background-color: #f5f7fa;
  margin: 0;
}

:deep(.el-tabs__nav) {
  border: none;
}

:deep(.el-tabs__item) {
  font-size: 14px;
  height: 40px;
  line-height: 40px;
  border: none;
  margin-top: -1px;
}

:deep(.el-tabs__item.is-active) {
  font-weight: bold;
  background-color: #fff;
}

:deep(.el-empty) {
  padding: 60px 0;
}

@media screen and (max-width: 768px) {
  .statistics-info {
    gap: 20px;
  }

  .time-info {
    font-size: 12px;
  }

  .table-container {
    padding: 5px;
  }

  :deep(.el-table__row) {
    height: 40px;
  }
}

:deep(.el-tag.el-tag--danger) {
  background-color: var(--el-color-danger-light-9);
  border-color: var(--el-color-danger-light-5);
  color: var(--el-color-danger);
}

:deep(.el-tag.el-tag--warning) {
  background-color: var(--el-color-warning-light-9);
  border-color: var(--el-color-warning-light-5);
  color: var(--el-color-warning);
}

:deep(.el-tag.el-tag--info) {
  background-color: var(--el-color-info-light-9);
  border-color: var(--el-color-info-light-5);
  color: var(--el-color-info);
}
</style> 